package com.seecoder.BlueWhale.serviceImpl.payStrategy;

import com.seecoder.BlueWhale.configure.AlipayTools;
import com.seecoder.BlueWhale.enums.CouponStatusEnum;
import com.seecoder.BlueWhale.enums.OrderStatusEnum;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.Commodity;
import com.seecoder.BlueWhale.po.Coupon;
import com.seecoder.BlueWhale.po.CouponGroup;
import com.seecoder.BlueWhale.po.Order;
import com.seecoder.BlueWhale.repository.*;
import com.seecoder.BlueWhale.serviceImpl.CouponGroupServiceImpl;
import com.seecoder.BlueWhale.util.JsonUtil;
import com.seecoder.BlueWhale.util.SecurityUtil;
import com.seecoder.BlueWhale.vo.DiscountParams;
import com.seecoder.BlueWhale.vo.PayParams;
import com.seecoder.BlueWhale.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class TestSuccessPay implements PayStrategy {

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    CommodityRepository commodityRepository;

    @Autowired
    CouponRepository couponRepository;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    CouponGroupRepository couponGroupRepository;

    @Autowired
    CouponGroupServiceImpl couponGroupServiceImpl;

    @Autowired
    AlipayTools alipayTools;

    @Override
    public boolean pay(PayParams params, HttpServletResponse httpServletResponse) {
        List<Integer> couponID = params.getCouponID();
        Order order = orderRepository.findById(params.getOrderID());

        if (order == null) {
            throw BlueWhaleException.orderNotFound();
        } else if (order.getStatus() != OrderStatusEnum.UNPAID) {
            throw BlueWhaleException.orderStatusWrong();           //订单状态异常
        }

        Commodity commodity = commodityRepository.findById(order.getCommodityID().intValue());
        double price = commodity.getPrice() * order.getQuantity();
        List<Coupon> coupons = couponID.stream().map(a -> couponRepository.findById(a.intValue())).collect(Collectors.toList());

        if (!couponID.isEmpty()) {
            if (coupons.stream().anyMatch(coupon -> {
                boolean flag = false;
                //使用过或不是自己的优惠券
                flag |= (coupon.getCouponStatus() == CouponStatusEnum.USED
                        || coupon.getUserId() != securityUtil.getUserId());
                CouponGroup couponGroup = couponGroupRepository.findById(coupon.getCouponGroupId());
                //不是全局且不是该商店的优惠券
                flag &= (couponGroup.getStoreId() != 0 && couponGroup.getStoreId() != order.getStoreID());
                return flag;
            })) {
                throw BlueWhaleException.invalidCoupon();
            } else {
                price = couponGroupServiceImpl.discount(new DiscountParams(price, coupons.stream().map(Coupon::getCouponGroupId).collect(Collectors.toList())));
            }
        }
        order.setStatus(OrderStatusEnum.UNSEND);
        orderRepository.save(order);
        for (Coupon coupon : coupons) {
            coupon.setCouponStatus(CouponStatusEnum.USED);
            couponRepository.save(coupon);
        }
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            PrintWriter printWriter = httpServletResponse.getWriter();
            ResultVO<Boolean> resultVO = ResultVO.buildSuccess(true);
            printWriter.write(JsonUtil.object2Json(resultVO));
        } catch (IOException ioException) {
            log.error("response error");
            ioException.printStackTrace();
        }
        return true;
    }
}
